package bzapps.weynak.ar.com.jwetherell.augmented_reality.data;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import bzapps.weynak.R;
import bzapps.weynak.ar.com.jwetherell.augmented_reality.ui.IconMarker;
import bzapps.weynak.ar.com.jwetherell.augmented_reality.ui.Marker;

/**
 * This class extends DataSource to fetch data from Google Buzz.
 * 
 * @author Justin Wetherell <phishman3579@gmail.com>
 */
public class WeynakDataSource extends DataSource {
	private static final Logger logger = Logger.getLogger(WeynakDataSource.class.getSimpleName());
	private static final String BASE_URL = "http://www.bz-apps.com/weynak/locations.php";

	private static Bitmap icon = null;
	
	public WeynakDataSource(Resources res) {
		if (res==null) return;
		
		createIcon(res);
	}
	
	protected void createIcon(Resources res) {
		if (res==null) return;
		
		icon=BitmapFactory.decodeResource(res, R.drawable.frame);
	}
	
	public Bitmap getBitmap() {
		return icon;
	}
	
	public String createRequestURL(double lat, double lon, double alt, float radius, String locale) {
		return BASE_URL+
		"?loc=retrieve&uid=8";
	}
	
	public Marker processJSONObject(JSONObject jo) {		
        Marker ma = null;
        	try {
        		ma = new IconMarker(
        				jo.getString("name"),
        				jo.getDouble("latitude"),
        				jo.getDouble("longitude"),
        				
        				0,
        				Color.GREEN,
        				icon);
//        		logger.info("longitude: "+jo.getDouble("longitude"));
        	} catch (Exception e) {
        		logger.info("Exception marker: "+e.getMessage());
        	}
        
        return ma;
	}

	@Override
	public List<Marker> parse(JSONArray root) {
		JSONObject jo = null;
    	List<Marker> markers=new ArrayList<Marker>();

		try {;
			int top = root.length();
				for (int i = 0; i < top; i++) {					
					jo = root.getJSONObject(i);
					Marker ma = processJSONObject(jo);
					if(ma!=null) markers.add(ma);
				}
		} catch (JSONException e) {
			logger.info("Exception list: "+e.getMessage());
		}
		return markers;
	}
}
